package com.example.question.array;

/**
 * @Date 2023-08-05
 * @Author Jonathan
 */
public class Code07_80 {


    public static void main(String[] args) {
        Code07_80 code0780 = new Code07_80();
        int i = code0780.removeDuplicates(new int[]{0, 0, 1, 1, 1, 1, 2, 3, 3});
        System.out.println(i);
    }

    /**
     * 空间复杂度O(n)的解法
     */
    public int removeDuplicates1(int[] nums) {
        int[] countMap = new int[20000];
        for (int num : nums) {
            int index = (num + 9999);
            countMap[index]++;
        }

        int index = 0;
        // 将元元素放回去
        for (int i = 0; i < countMap.length; i++) {
            for (int j = 0; j < Math.min(2, countMap[i]); j++) {
                nums[index++] = i - 9999;
            }
        }
        return index;
    }

    public int removeDuplicates(int[] nums) {
        return process(nums, 2);
    }


    int process(int[] nums, int k) {
        int u = 0;
        for (int i = 0; i < nums.length; i++) {
            if (u < k || nums[u - k] != nums[i]) {
                nums[u++] = nums[i];
            }
        }
        return u;
    }
}
